class Customer < ActiveRecord::Base

  after_create :generate_customer_no
  
  belongs_to :card
  belongs_to :title
  belongs_to :nationality
  belongs_to :province , :class_name => "issue_province"
  belongs_to :occupation
  
  belongs_to :branch

  has_many :agreements

  has_attached_file :image, :styles => { :medium => "300x300#", :thumb => "100x100#" }

  validates_presence_of :title,:first_name,:last_name,:marr_status,:birth_date,:nationality
  validates_presence_of :card,:card_no,:issue_by,:issue_province,:issue_date,:issue_expire
  
  validates_presence_of :register_address,:register_tel_no,:register_home_live,:register_home_position
  validates_presence_of :register_home_characteristic #,:register_home_near
  validates_presence_of :present_address,:present_tel_no,:present_home_live,:present_home_position
  validates_presence_of :present_home_characteristic #,:present_home_near
  
  validates_presence_of :occupation_id,:work_position,:work_name,:work_address,:work_tel_no,:work_start,:work_salary,:other_income
  
  validates_presence_of :married_name,:married_occupation_id,:married_work_position,:married_work_name,:married_work_address,:married_work_tel_no,:married_work_start,:married_work_salary,:married_other_income, :if => Proc.new { |c| c.marr_status == 'Married' }

  validates_presence_of :branch_id

  validates_uniqueness_of :code

  validates_length_of :first_name,:last_name,:nick_name , :maximum =>128

  #validates_attachment_presence :image
  validates_attachment_size :image, :less_than => 5.megabytes
  validates_attachment_content_type :image, :content_type => ['image/jpeg', 'image/png', 'image/gif']

  cattr_reader :per_page

  def to_s
    return self.code  
  end
  
  def to_combo
    return [self.code+' ('+self.first_name+')',self.id]  
  end
  
  attr_accessor :user_log
  def to_audit
    return "ID:#{id}"+","+"Code:#{code}"+","+"First name:#{first_name}"+","+"Last name:#{last_name}"
  end
  
  private
  def generate_customer_no
    self.code = Time.now.strftime("%Y")+"-"+self.branch.code+"-"+"%05d"%self.id
    self.save
  end
  
end
